import React, {useCallback} from 'react';
import {DatePicker, Button, Card, Dialog, Field, Icon, List, Message, Pagination, Table} from '@alifd/next';
import {useFusionTable, useSetState} from 'ahooks';

import {request} from 'ice';
import {datetimeStamp2String} from '@/utils/locale';
import EmptyBlock from './EmptyBlock';
import ExceptionBlock from './ExceptionBlock';
import DialogOperation from './DialogOperation';
import {ActionType, OperaitionProps} from './Operation';

import styles from './index.module.scss';

const getTableData = (
  {current, pageSize}: { current: number; pageSize: number },
  formData: { status: 'normal' | 'empty' | 'exception' }
): Promise<any> => {
  if (!formData.status || formData.status === 'normal') {
    let query = `current=${current}&size=${pageSize}`;
    Object.entries(formData).forEach(([key, value]) => {
      if (value) {
        query += `&${key}=${value}`
      }
    });
    const data = request({
      url: `/v1/admin/movie/mvm/?${query}`,
      method: 'get',
    });
    console.log('data', data);
    return data.then(res => {
      return {
        list: res.data.records,
        total: res.data.total
      }
    })
  }
  if (formData.status === 'empty') {
    return Promise.resolve([]);
  }
  if (formData.status === 'exception') {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        reject(new Error('data exception'));
      }, 1000);
    });
  }

  return Promise.resolve([]);
};

interface ColumnWidth {
  id: number;
  subject: number;
  secondSubject: number;
  text: number;
  date: number;
  operation: number;
}

interface DialogState {
  columnWidth: ColumnWidth;
  optCol: any;
  actionType: ActionType;
  actionVisible: boolean;
}

const defaultColumnWidth: ColumnWidth = {
  id: 200,
  subject: 200,
  secondSubject: 200,
  text: 500,
  date: 200,
  operation: 50,
};

const DialogTable: React.FC = () => {
  const [state, setState] = useSetState<DialogState>({
    columnWidth: defaultColumnWidth,
    optCol: null,
    actionType: 'preview',
    actionVisible: false,
  });
  const {actionVisible, columnWidth, optCol} = state;
  const field = Field.useField([]);
  const {paginationProps, tableProps, search, error, refresh} = useFusionTable(getTableData, {
    field,
  });

  const {reset} = search;

  const onResizeChange = (dataIndex: keyof typeof defaultColumnWidth, width: number) => {
    const newWidth = {
      ...columnWidth,
    };
    newWidth[dataIndex] += width;
    setState({columnWidth: newWidth});
  };

  const operationCallback = useCallback(({actionType, dataSource}: OperaitionProps): void => {
    setState({
      actionType,
      optCol: dataSource,
      actionVisible: true,
    });
  }, [setState]);

  const handleCancel = useCallback((): void => {
    setState({actionVisible: false});
  }, [setState]);

  const handleOk = useCallback((): void => {
    const {actionType, optCol} = state;
    if (actionType === 'preview') {
      handleCancel();
      return;
    }
    Message.success(actionType === 'add' ? '添加成功!' : '编辑成功!');
    reset();
    handleCancel();
  }, [handleCancel, reset, state]);

  const handleDelete = useCallback((data: any) => {
    if (!data) {
      return;
    }
    Dialog.confirm({
      title: '删除提醒',
      content: `确定删除 ${data.subject} 吗`,
      async onOk() {
        console.log(data);
        reset();
      }
    });
  }, [reset]);

  const cellOperation = (...args: any[]): React.ReactNode => {
    const record = args[2];
    return (
      <div>
        <Button
          text
          type="primary"
          onClick={() => operationCallback({actionType: 'edit', dataSource: record})}
        >
          编辑
        </Button>

        &nbsp;&nbsp;
        {/* <Button
          text
          type="primary"
          onClick={() => handleDelete(record)}
        >
          删除
        </Button> */}

        {/*
        <Button
          text
          type="primary"
          onClick={() => operationCallback({ actionType: 'preview', dataSource: record })}
        >
          查看
        </Button> */}
      </div>
    );
  };

  const castGmtCreat = (...args: any[]) => {
    const arg = args[0];
    if (arg) {
      return datetimeStamp2String(arg);
    } else {
      return '';
    }
  }
  const castBoolean = (...args: any[]) => {
    const arg = args[0];
    if (arg != null) {
      return arg ? '是' : '否';
    } else {
      return '';
    }
  }

  return (
    <div className={styles.DialogTable}>
      <List>
        <List.Item>
          <div>
            <Button
              type="primary"
              onClick={() => operationCallback({actionType: 'add', dataSource: {}})}
            >
              <Icon type="add"/>
              新增
            </Button>
          </div>
        </List.Item>
      </List>

      <Card free>
        <Card.Content>
          <Table
            {...tableProps}
            onResizeChange={onResizeChange}
            emptyContent={error ? <ExceptionBlock onRefresh={refresh}/> : <EmptyBlock/>}
            primaryKey="email"
          >
            <Table.Column title="电影ID" dataIndex="id" resizable width={columnWidth.id}/>
            <Table.Column title="电影名" dataIndex="name" resizable width={columnWidth.id}/>
            <Table.Column title="电影海报地址" dataIndex="icon" resizable width={columnWidth.id}/>
            <Table.Column title="电影简介" dataIndex="detail" resizable width={columnWidth.id}/>
            <Table.Column title="电影市场(分)" dataIndex="time" resizable width={columnWidth.id}/>
            {/* <Table.Column title="可见时间" dataIndex="date" cell={castGmtCreat} resizable
                          width={columnWidth.date}/>
            <Table.Column title="创建时间" dataIndex="gmtCreat" cell={castGmtCreat} resizable
                          width={columnWidth.date}/>
            <Table.Column title="修改时间" dataIndex="gmtModified" cell={castGmtCreat} resizable
                          width={columnWidth.date}/> */}
            <Table.Column title="操作" resizable width={columnWidth.operation} cell={cellOperation}/>
          </Table>
          <Pagination pageSizeList={[10, 20]} pageSizeSelector="filter" style={{marginTop: 16, textAlign: 'right'}}
                      totalRender={total => <>共 <Button text
                                                        type="primary">{total}</Button> 个记录</>}  {...paginationProps} />
        </Card.Content>
      </Card>
      <DialogOperation
        visible={actionVisible}
        actionType={state.actionType}
        dataSource={optCol}
        onOk={handleOk}
        onClose={handleCancel}
        onCancel={handleCancel}
      />
    </div>
  );
}

export default DialogTable;
